package com.yyfax.common.form;

import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.yyfax.common.CLog;
import com.yyfax.common.R;
import com.yyfax.common.tools.DensityUtil;
import com.yyfax.common.tools.Toaster;

import java.lang.reflect.Constructor;

/**
 * Created by fuqiang on 2017/4/28.
 * 自定义表单类，左边是textview，右边是edittext或者textview
 * Copyright  2017 www.yylending.com. All Rights Reserved.
 */
public class FormRow extends LinearLayout {
	private static final String TAG = "FormRow";

	/**
	 * 左边textview的颜色
	 */
	private ColorStateList mLeftTextColor;

	/**
	 * 左边的textView
	 */
	protected TextView mLeftTextView;

	/**
	 * 左边textview的宽度
	 */
	private int mLeftWidth;

	/**
	 * 普通输入框校验的处理者
	 */
	private FormRowControl mNormalControl;

	/**
	 * 下拉选择框校验的处理者
	 */
	private FormRowControl mSelectControl;

	/**
	 * 公司座机校验的处理者
	 */
	private FormRowControl mLandlineControl;

	/**
	 * 身份证校验的处理者
	 */
	private FormRowControl mIdCardControl;

	/**
	 * 手机号码校验的处理者
	 */
	private FormRowControl mPhoneControl;

	/**
	 * 银行卡校验的处理者
	 */
	private FormRowControl mBankCardControl;

	/**
	 * 金额校验的处理者
	 */
	private FormRowControl mAmountControl;

	/**
	 * 配置的表单的类型
	 */
	private int mType;

	/**
	 * 反馈的提示信息
	 */
	public NoticeText noticeText;

	/**
	 * 带删除图标的EditText
	 */
	public ClearEditText mClearEditText;

	/**
	 * 选择文本表单
	 */
	public FormSelectView mFormSelectView;

	/**
	 * 带扫描按钮的输入框
	 */
	public FormScanView mFormScanView;

	/**
	 * 座机输入框
	 */
	public FormLandLineView mFormLandLineView;
	private boolean mCanEdit = true;//能否编辑身份证

	public FormRow(Context context) {
		super(context);
	}

	public FormRow(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context, attrs);
	}

	public FormRow(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		init(context, attrs);
	}

	private void init(Context context, AttributeSet attrs) {
		setOrientation(LinearLayout.HORIZONTAL);
		ClassTypeSingleton.getSingleton();
		noticeText = new NoticeText();

		TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.FormRow);
		mType = ta.getInt(R.styleable.FormRow_customType, 3);

		//根据配置得到反馈的提示语
		String emptyFormat = ta.getString(R.styleable.FormRow_emptyFormat);
		String emptyKeyword = ta.getString(R.styleable.FormRow_emptyKeyword);
		//内容为空时的提示内容，"xxx不能为空"，在XML文件中配置提示的关键字
		if (emptyFormat != null) {
			noticeText.mEmptyMsg = String.format(emptyFormat, emptyKeyword);
		}
		String expressionFormat = ta.getString(R.styleable.FormRow_expressionFormat);
		String expressionKeyword = ta.getString(R.styleable.FormRow_expressionKeyword);
		//内容格式错误时的提示内容，"xxx不能为空"，在XML文件中配置提示的关键字
		if (expressionFormat != null) {
			noticeText.mExpressionMsg = String.format(expressionFormat, expressionKeyword);
		}

		noticeText.mOverRangeMsg = ta.getString(R.styleable.FormRow_overRange);
		noticeText.mAmountMsg = ta.getString(R.styleable.FormRow_amount);

		mLeftWidth = ta.getDimensionPixelSize(R.styleable.FormRow_leftWidth, DensityUtil.dip2px(context, (100 - 14)));
		//字体大小，左边和右边的textview一样
		float mTextSize = ta.getDimension(R.styleable.FormRow_leftTextSize, DensityUtil.sp2px(getContext(), 15));//设置textsize
		mLeftTextView = new TextView(context);
		mLeftTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize);
		mLeftTextColor = ta.getColorStateList(R.styleable.FormRow_leftTextColor);//设置textcolor
		if (mLeftTextColor != null)
			mLeftTextView.setTextColor(mLeftTextColor);
		else
			mLeftTextView.setTextColor(getResources().getColor(R.color.color_333333));
		mLeftTextView.setGravity(Gravity.CENTER_VERTICAL);
		mLeftTextView.setText(ta.getString(R.styleable.FormRow_leftText));//设置text
		addView(mLeftTextView);

		//根据type来动态add右边的view
		String className = ClassTypeSingleton.getSingleton().getClassNames().get(mType);
		if (className != null) {
			try {
				Class clazz = Class.forName(className);
				Constructor constructor = clazz.getConstructor(Context.class, AttributeSet.class);
				if (className.contains("ClearEditText")) {
					mClearEditText = (ClearEditText) constructor.newInstance(context, attrs);
					mClearEditText.setSingleLine(true);
					float textSize = ta.getDimension(R.styleable.FormRow_textSize, DensityUtil.sp2px(getContext(), 15));
					mClearEditText.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
					int paddingLeft = ta.getDimensionPixelSize(R.styleable.FormRow_ClearEditTextPaddingLeft, 0);
					int paddingRight = ta.getDimensionPixelSize(R.styleable.FormRow_ClearEditTextPaddingRight, 0);
					mClearEditText.setPadding(paddingLeft, getPaddingTop(), paddingRight, getPaddingBottom());
					addView(mClearEditText);
				} else if (className.contains("FormSelectView")) {
					mFormSelectView = (FormSelectView) constructor.newInstance(context, attrs);
					int paddingLeft = ta.getDimensionPixelSize(R.styleable.FormRow_FormSelectViewPaddingLeft, 0);
					int paddingRight = ta.getDimensionPixelSize(R.styleable.FormRow_FormSelectViewPaddingRight, 0);
					mFormSelectView.setPadding(paddingLeft, getPaddingTop(), paddingRight, getPaddingBottom());
					addView(mFormSelectView);
				} else if (className.contains("FormScanView")) {
					mFormScanView = (FormScanView) constructor.newInstance(context, attrs);
					int paddingLeft = ta.getDimensionPixelSize(R.styleable.FormRow_FormScanViewPaddingLeft, 0);
					int paddingRight = ta.getDimensionPixelSize(R.styleable.FormRow_FormScanViewPaddingRight, 0);
					mFormScanView.setPadding(paddingLeft, getPaddingTop(), paddingRight, getPaddingBottom());
					addView(mFormScanView);
				} else if (className.contains("FormLandLineView")) {
					mFormLandLineView = (FormLandLineView) constructor.newInstance(context, attrs);
					addView(mFormLandLineView);
				}

			} catch (Exception e) {
				//e.printStackTrace();
				CLog.e(TAG, e.toString());
			}
			mNormalControl = new NormalControl();
			mSelectControl = new SelectControl();
			mLandlineControl = new LandLineControl();
			mIdCardControl = new IdCardControl();
			mPhoneControl = new PhoneControl();
			mBankCardControl = new BankCardControl();
			mAmountControl = new AmountControl();
			mNormalControl.setFormRowControl(mSelectControl);
			mSelectControl.setFormRowControl(mLandlineControl);
			mLandlineControl.setFormRowControl(mIdCardControl);
			mIdCardControl.setFormRowControl(mPhoneControl);
			mPhoneControl.setFormRowControl(mBankCardControl);
			mBankCardControl.setFormRowControl(mAmountControl);
		}
		ta.recycle();
	}

	/**
	 * 释放内存,建议在退出应用或者不再使用该view时使用
	 */
	public void destory() {
		mNormalControl = null;
		mSelectControl = null;
		mLandlineControl = null;
		mIdCardControl = null;
		mPhoneControl = null;
		mBankCardControl = null;
		mAmountControl = null;
	}

	/**
	 * 合法性检查
	 */
	public boolean validate() {
		if (mNormalControl != null) {
			return mNormalControl.toastControl(mType, this, noticeText);
		}
		Toaster.showShortToast(getContext(), R.string.unknown_error);
		return false;
	}

	/**
	 * 根据配置获取FormRow右边的View
	 */
	public View getRightView() {
		switch (mType) {
			case 3:
			case 8:
			case 10:
				return mClearEditText;
			case 4:
			case 5:
				return mFormSelectView;
			case 7:
			case 9:
				return mFormScanView;
			case 6:
				return mFormLandLineView;
		}
		return null;
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		View leftChild = getChildAt(0);
		leftChild.measure(MeasureSpec.makeMeasureSpec(mLeftWidth, MeasureSpec.EXACTLY), heightMeasureSpec);
		int mRightWidth = MeasureSpec.getSize(widthMeasureSpec) - mLeftWidth;

		View rightChild = getChildAt(1);
		if (rightChild != null)
			rightChild.measure(MeasureSpec.makeMeasureSpec(mRightWidth, MeasureSpec.EXACTLY), heightMeasureSpec);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_UP)
			CLog.i(TAG, "MotionEvent.ACTION_UP");
		return super.onTouchEvent(event);
	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		super.onLayout(changed, l, t, r, b);
		int childCount = getChildCount();
		View childView0 = getChildAt(0);
		View childView1 = getChildAt(1);

		childView1.layout(l + childView0.getMeasuredWidth(), childView0.getTop(), l + childView0.getMeasuredWidth() + childView1.getMeasuredWidth(), childView0.getBottom());

//        int mTotalLength = getPaddingLeft()+l;
//        for (int i = 0; i < childCount; i++) {
//            View childView = getChildAt(i);
//            int measureHeight = childView.getMeasuredHeight();
//            int measureWidth = childView.getMeasuredWidth();
//            childView.layout(mTotalLength, t, mTotalLength+measureWidth, b);
//            mTotalLength+= measureWidth;
//        }
	}

	/**
	 * 设置文本
	 */
	public void setText(CharSequence text) {
		switch (mType) {
			case 3:
			case 8:
			case 10:
				mClearEditText.setText(text);
				break;
			case 4:
			case 5:
				mFormSelectView.setText(text);
				break;
			case 7:
			case 9:
				mFormScanView.setText(text);
				break;
		}
	}

	/**
	 * 获取文本
	 */
	public String getText() {
		switch (mType) {
			case 3:
			case 8:
			case 10:
				return mClearEditText.getFormText();
			case 4:
			case 5:
				return mFormSelectView.getFormText();
			case 7:
			case 9:
				return mFormScanView.getFormText();
		}
		return null;
	}

	/**
	 * Set the visibility state of this view.
	 *
	 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
	 * @attr ref android.R.styleable#View_visibility
	 */
	@Override
	public void setVisibility(int visibility) {
		super.setVisibility(visibility);
		if (mLeftTextView != null) {
			mLeftTextView.setVisibility(visibility);
		}
		View right = getRightView();
		if (right != null) {
			right.setVisibility(visibility);
		}
	}

	//如果edittext不能编辑，则在外面拦截点击事件
	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		if (!mCanEdit)
			return true;
		return super.onInterceptTouchEvent(ev);
	}

	public void setmCanEdit(boolean mCanEdit) {
		this.mCanEdit = mCanEdit;
	}
}
